package com.example.campuslink.ui.activity

import android.content.Intent
import android.graphics.BitmapFactory
import android.os.Bundle
import android.provider.MediaStore
import android.util.Log
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.databinding.ActivityScanBinding
import com.example.campuslink.viewModel.ScanViewModel
import com.google.zxing.BarcodeFormat
import com.google.zxing.BinaryBitmap
import com.google.zxing.DecodeHintType
import com.google.zxing.MultiFormatReader
import com.google.zxing.RGBLuminanceSource
import com.google.zxing.common.HybridBinarizer
import com.journeyapps.barcodescanner.BarcodeCallback
import com.journeyapps.barcodescanner.CaptureManager
import com.journeyapps.barcodescanner.DecoratedBarcodeView
import com.journeyapps.barcodescanner.DefaultDecoderFactory
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.Hashtable

class ScanActivity : BaseActivity<ActivityScanBinding, ScanViewModel>(
    ScanViewModel::class.java,
    R.layout.activity_scan,
    BR.viewModel
) {
    private val PICK_IMAGE_REQUEST = 1
    private lateinit var captureManager: CaptureManager
    private var savedInstanceState: Bundle = Bundle()
    private var barcodeView: DecoratedBarcodeView? = null
    override fun initView() {
        lifecycleScope.launch(Dispatchers.IO) {
            init()
        }
        this.savedInstanceState = savedInstanceState
        mViewDataBinding?.btnOpenCamera?.setOnClickListener({
            openGallery()
        })
        barcodeView = mViewDataBinding?.dbvScan as DecoratedBarcodeView
        setupScanner()
    }

    fun init() {
        mViewModel?.initDB(this)
    }

    fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            val selectedImageUri = data.data
            val projection = arrayOf(MediaStore.Images.Media.DATA)
            val cursor = contentResolver.query(selectedImageUri!!, projection, null, null, null)
            if (cursor != null) {
                if (cursor.moveToFirst()) {
                    val columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)
                    val imagePath = cursor.getString(columnIndex)
                    parsePhoto(imagePath)
                }
                cursor.close()
            }
        }
    }

    fun parsePhoto(photoPath: String?) {
        try {
            val options = BitmapFactory.Options()
            options.inJustDecodeBounds = false
            val bitmap = BitmapFactory.decodeFile(photoPath, options)

            if (bitmap != null) {
                val width = bitmap.width
                val height = bitmap.height
                val pixels = IntArray(width * height)
                bitmap.getPixels(pixels, 0, width, 0, 0, width, height)
                val source = RGBLuminanceSource(width, height, pixels)
                val binaryBitmap = BinaryBitmap(HybridBinarizer(source))
                val reader = MultiFormatReader()
                reader.setHints(Hashtable<DecodeHintType, Any?>())
                val result = reader.decode(binaryBitmap)
                if (result != null) {
                    val content = result.text
                    handleResult(content)
                } else {
                    Toast.makeText(this, "未识别到二维码", Toast.LENGTH_SHORT).show()
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Toast.makeText(this, "二维码解析失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun setupScanner() {
        val formats: MutableList<BarcodeFormat> = ArrayList()
        formats.add(BarcodeFormat.QR_CODE)
        formats.add(BarcodeFormat.CODE_39)
        // 可以添加更多条形码和二维码格式
        barcodeView?.getBarcodeView()?.setDecoderFactory(DefaultDecoderFactory(formats))
        captureManager = CaptureManager(this, barcodeView)
        captureManager.initializeFromIntent(intent, savedInstanceState)
        captureManager.decode()
        barcodeView?.decodeContinuous(BarcodeCallback { result -> handleResult(result.text) })
    }

    private fun handleResult(result: String) {
        lifecycleScope.launch(Dispatchers.IO) {
            mViewModel?.getNowNumberInfo(result)
        }

        mViewModel?.schoolUserNumber?.observe(this) {
            if (it != null && it.schoolUser.contains(result) && result != (Sp.getString(
                    this,
                    "userNumber",
                    ""
                ))
            ) {
                mViewModel?.jumpToUserMainActivity(result)
            } else if (result == (Sp.getString(this, "userNumber", ""))) {
                Toast.makeText(this, "无法跳转到自己的账号", Toast.LENGTH_SHORT).show()
            } else {
                Toast.makeText(this, "用户不存在", Toast.LENGTH_SHORT).show()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        captureManager.onResume()
    }

    override fun onPause() {
        super.onPause()
        captureManager.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        captureManager.onDestroy()
    }
}